/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.testingProject.view;

import java.awt.Color;
import javax.swing.JOptionPane;
import org.colswe.testingProject.control.AuthenticationControl;
import org.colswe.testingProject.control.CRUDUsersControl;
import org.colswe.testingProject.control.PersonControl;
import org.colswe.testingProject.entity.Person;

/**
 *
 * @author Leonardo Bohórquez
 */
public class EditUserPanel extends javax.swing.JPanel {

    /**
     * Creates new form EditUserPanel
     */
    private boolean flag;
    private PersonControl pc;
    private CRUDUsersControl cruduc;
    private AuthenticationControl ac;

    public EditUserPanel(boolean flag, String userName) {
        initComponents();
        this.flag = flag;
        pc = new PersonControl();
        cruduc = new CRUDUsersControl();
        ac = new AuthenticationControl();
        if (flag) {
            cmdButton.setText("Crear");
        } else {
            cmdButton.setText("Guardar");
            LoginWindow.mf.tbpnlTabs.setTitleAt(LoginWindow.mf.tbpnlTabs.getTabCount() - 1,
                    "Editar usuario");
            LoginWindow.mf.tbpnlTabs.setEnabled(false);
            txtUsername.setText(userName);
            txtUsername.setEditable(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtPasswordConf = new javax.swing.JPasswordField();
        txtPassword = new javax.swing.JPasswordField();
        txtUsername = new javax.swing.JTextField();
        cboRol = new javax.swing.JComboBox();
        lblMsgUser = new javax.swing.JLabel();
        lblMsgPass = new javax.swing.JLabel();
        lblMsgPassConf = new javax.swing.JLabel();
        cmdButton = new javax.swing.JButton();
        cmdCancel = new javax.swing.JButton();

        jLabel1.setText("Nombre de usuario");
        jLabel1.setFocusable(false);

        jLabel2.setText("Contraseña");
        jLabel2.setFocusable(false);

        jLabel3.setText("Confirmar contraseña");
        jLabel3.setFocusable(false);

        jLabel4.setText("Rol");
        jLabel4.setFocusable(false);

        txtPasswordConf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPasswordConfActionPerformed(evt);
            }
        });

        cboRol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador de usuarios", "Administrador", "Secretaria de la Coordinación Curricular", "Asistente de la Coordinación Curricular" }));

        cmdButton.setText("Boton");
        cmdButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdButtonActionPerformed(evt);
            }
        });

        cmdCancel.setText("Cancelar");
        cmdCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPassword)
                            .addComponent(cboRol, 0, 157, Short.MAX_VALUE)
                            .addComponent(txtUsername)
                            .addComponent(txtPasswordConf)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmdButton)
                        .addGap(18, 18, 18)
                        .addComponent(cmdCancel)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMsgUser, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .addComponent(lblMsgPass, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblMsgPassConf, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMsgUser))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMsgPass))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtPasswordConf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMsgPassConf))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cboRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdButton)
                    .addComponent(cmdCancel))
                .addContainerGap(139, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtPasswordConfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordConfActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPasswordConfActionPerformed

    private void cmdCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelActionPerformed
        LoginWindow.mf.tbpnlTabs.setEnabled(true);
        LoginWindow.mf.tbpnlTabs.remove(this);
    }//GEN-LAST:event_cmdCancelActionPerformed

    private String role(String role) {
        if (role.equals("Administrador")) {
            role=Person.ADMINISTRATOR;
        } else if (role.equals("Administrador de usuarios")) {
            role=(Person.USERS_ADMINISTRATOR);
        } else if(role.equals("Secretaria de la Coordinación Curricular")) {
            role=(Person.SEC_COO);
        } else {
            role=(Person.ASIS_COO);
        }
        return role;
    }
    
    private void execute() {
        if (flag) {//Si se entra en modo de creación de usuarios
            int option = JOptionPane.showConfirmDialog(null, "Desea crear el usuario \""
                    + txtUsername.getText() + "\"", "Dialogo de confirmación", JOptionPane.YES_NO_OPTION);
            if (option == 0) {
                boolean result = pc.create(new Person(txtUsername.getText().toLowerCase(),
                        new String(txtPassword.getPassword()), role(cboRol.getSelectedItem().toString())));
                if (result) {
                    JOptionPane.showMessageDialog(null, "Se ha creado el usuario \""
                            + txtUsername.getText() + "\"", "Creación de usuario exitosa",
                            JOptionPane.INFORMATION_MESSAGE);
                    LoginWindow.mf.pnlAdminUser.tblUsers.setModel(cruduc.showResults(null, null));
                    LoginWindow.mf.tbpnlTabs.setEnabled(true);
                    LoginWindow.mf.tbpnlTabs.remove(this);
                } else {
                    JOptionPane.showMessageDialog(null, "Hubo un error al intentar crear el usuario",
                            "Error", JOptionPane.ERROR_MESSAGE);
                }
            }


        } else {//Si se entra en modo de edición de usuarios
            int option = JOptionPane.showConfirmDialog(null, "Desea editar al usuario \""
                    + txtUsername.getText() + "\"", "Dialogo de confirmación", JOptionPane.YES_NO_OPTION);
            if (option == 0) {
                boolean result = pc.update(new Person(txtUsername.getText().toLowerCase(),
                        new String(txtPassword.getPassword()), role(cboRol.getSelectedItem().toString())));
                if (result) {
                    JOptionPane.showMessageDialog(null, "Se han guardado los cambios en el usuario \""
                            + txtUsername.getText() + "\"", "Modificación de usuario exitosa",
                            JOptionPane.INFORMATION_MESSAGE);
                    LoginWindow.mf.pnlAdminUser.tblUsers.setModel(cruduc.showResults(null, null));
                    LoginWindow.mf.tbpnlTabs.setEnabled(true);
                    LoginWindow.mf.tbpnlTabs.remove(this);
                } else {
                    JOptionPane.showMessageDialog(null,
                            "Hubo un error al intentar guardar las modificaciones en el usuario",
                            "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    private void cmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdButtonActionPerformed
        lblMsgPass.setText("");
        lblMsgPassConf.setText("");
        lblMsgUser.setText("");
        if (ac.passwordConfirmationValidation(new String(txtPassword.getPassword()),
                new String(txtPasswordConf.getPassword()))) {
            if (ac.passwordLengthValidation(new String(txtPassword.getPassword()))) {
                if (ac.passwordFormatValidation(new String(txtPassword.getPassword()))) {
                    if ((flag && ac.userNameUniquenessValidation(new Person(txtUsername.getText(), null, null))) || !flag) {
                        if ((flag && ac.userNameFormatValidation(txtUsername.getText())) || !flag) {
                            if ((flag && ac.userNameLengthValidation(txtUsername.getText())) || !flag) {
                                execute();
                            } else {
                                lblMsgUser.setText("El usuario debe tener entre 5 y 20 caracteres. ");
                                lblMsgUser.setForeground(Color.red);
                            }

                        } else {
                            lblMsgUser.setText(lblMsgUser.getText()+"El usuario no debe contener espacios. ");
                            lblMsgUser.setForeground(Color.red);
                        }
                    } else {
                        lblMsgUser.setText(lblMsgUser.getText() + "El usuario tiene que ser único");
                        lblMsgUser.setForeground(Color.red);
                    }
                } else {
                    lblMsgPass.setText("La contraseña debe contener caracteres alfanuméricos y "
                            + "al menos una letra mayúscula y un número");
                }
            } else {
                lblMsgPass.setText(lblMsgPass.getText()+"La longitud de la contraseña debe estar entre 5 y 30 caracteres");
                lblMsgPass.setForeground(Color.red);
            }
        } else {
            lblMsgPassConf.setText("Las contraseñas no coinciden");
            lblMsgPassConf.setForeground(Color.red);
        }
    }//GEN-LAST:event_cmdButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboRol;
    private javax.swing.JButton cmdButton;
    private javax.swing.JButton cmdCancel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblMsgPass;
    private javax.swing.JLabel lblMsgPassConf;
    private javax.swing.JLabel lblMsgUser;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPasswordConf;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
